package com.hckjsec.common.utils;

import com.hckjsec.common.config.JeeThinkConfig;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;


@RestController
public class ServletDownloadController {


    //文件流下载
    @GetMapping("/ServletDownload")
    public String flowout(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        OutputStream os = null;
        InputStream is = null;
        String Path=JeeThinkConfig.getProfile()+request.getParameter("filePath");//路径
        String filePath=Path.replace("/", "\\").trim();
        String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
        try{
            is = new FileInputStream(filePath);
            os = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" + buffer.length);
            os.write(buffer);
            os.flush();
            return "";
        }catch (Exception e) {
            e.printStackTrace();
            return "文件下载出错";
        }finally{
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
